<!--
 * @Author: your name
 * @Date: 2021-02-05 14:52:13
 * @LastEditTime: 2021-03-29 11:32:11
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue3-element-admin\src\views\layoutpages\system\Roles.vue
-->
<template>
    <div class="ve_container">

        <UserHeader></UserHeader>
        <!-- 搜索
        -->

        <!-- table工具条 -->
        <!--<el-row ref="toolBar" class="ve_header_row_class_name ve_p_10">
            <el-button
                v-permission="['add']"
                size="mini"
                type="primary"
                @click="handleEdit(menus.add.name)"
                >{{ menus.add.name }}</el-button
            >
        </el-row>-->
        <div>
            <div class="tab">
            </div>
            <div class="tab-value">
                <el-table :data="state.tableData" style="width: 100%">
          <el-table-column label="成员姓名">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                style="width: 70%"
                size="small"
                v-model="scope.row.nickname"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="是否启用">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                @change="changeStatus($event, scope.row.id)"
              ></el-switch>
            </template>
          </el-table-column>
          <!-- <el-table-column label="ID">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.id"
              ></el-input>
            </template>
          </el-table-column> -->
          <el-table-column label="账号">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.username"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="工号">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.number"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="密码">
            <template #default="scope">
              <el-input
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.pwd"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="薪资">
            <template #default="scope">
              <el-input
                v-if="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.salary_name"
                type="password"
                :show-password="true"
              ></el-input>
              <el-input
                v-else
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.salary"
              ></el-input>
            </template>
          </el-table-column>
           <el-table-column label="积分">
            <template #default="scope">
              <el-input
                v-if="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.integral"
                type="text"
              ></el-input>
              <el-input
                v-else
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.integral"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="余额">
            <template #default="scope">
              <el-input
                v-if="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.money"
                type="text"
              ></el-input>
              <el-input
                v-else
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.money"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="权限">
            <template #default="scope">
              <el-select
                v-if="scope.row.isEdit"
                size="small"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                style="width: 70%"
                v-model="scope.row.group_id"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in state.jurisdictionArr"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-input
                v-if="!scope.row.isEdit"
                :readonly="!scope.row.isEdit"
                style="width: 70%"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                size="small"
                v-model="scope.row.name"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="部门">
            <template #default="scope">
              <el-select
                :disabled="!scope.row.isEdit"
                size="small"
                :class="scope.row.isEdit ? '' : 'noEdit'"
                style="width: 70%"
                v-model="scope.row.department_id"
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in state.department"
                  :key="index"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>

            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template #default="scope">
              <div v-if="scope.row.isEdit" class="editing">
                <span @click="handleSave(scope.$index, scope.row)">保存</span>
                <span @click="handleCancle(scope.$index, scope.row)">取消</span>
              </div>
              <div v-if="!scope.row.isEdit" class="readOnly">
                <span @click="handleTabelRowEdit(scope.$index, scope.row)">编辑</span>
                <span @click="handleDelete(scope.row.id)">删除</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

                <div class="addUser" @click="addUser"><strong>+</strong>新增成员</div>

                <div class="pagin">
                    <!-- 分页 -->
                    <el-pagination v-if="state.tableData.length" layout="prev, pager, next"  
                        @current-change="handleCurrentChange"
                        :current-page="params.page"
                        :page-size="params.limit" 
                        :total="state.total">
                    </el-pagination>
                </div>
            </div>


        </div>
    </div>
</template>

<script>
    import RoleEdit from "./components/RoleEdit";
    import UserHeader from "@/components/common/user-header";
    import {
        reactive,
        toRefs,
        computed,
        ref,
        onMounted,
        getCurrentInstance
    } from "vue";
    import { useRoute, useRouter } from "vue-router";
    import { createLogger, useStore } from "vuex";
    import { findName } from "../common";
    import { getAdminList,deleteAdminListRow,departList,addAdmin,editAdmin,getGroups,changeStatusAdmin } from "@/request/api";
    
    
    //*导入公共查询方法
    import {
        onSubmit,
        resetForm,
        handleSizeChange,
        rowClassName,
        cellClassName,
        rowClick,
        maxHeight
    } from "@/views/layoutpages/common";

    const state = reactive({
        tableData:[],
        total:'',
        department:[],
        addIndex: -1,
        adding: false,
        jurisdictionArr: [],

    })
    export default {
        data: () => ({
            description: "角色信息查询与设置",
            menus: {
                search: { name: "查询" },
                add: { name: "添加" },
                edit: { name: "编辑" },
                del: { name: "删除" },
                member: { name: "查看成员", toPath: true }
            }
        }),
        components: {
            // RoleEdit,
            UserHeader
        },
        setup(props, { emit }) {
            const  ctx  = getCurrentInstance();
            const _this = ctx.appContext.config.globalProperties;
            const { proxy } = getCurrentInstance();
            const route = useRoute();
            const router = useRouter();
            const store = useStore();
            const menuList = computed(() => store.getters.menuList).value;
            const value1 = true
            const rowData = ref(null);
            const dialogTitle = ref("");
            const showDialog = ref(false);
            const ve_max_height = ref(0);
            const ve_rowIndex = ref(null);
            const toolBar = ref(null);
            const pagination = ref(null);
            const queryForm = ref(null);
            const tableData = ref([]);
            const params = reactive({
                name: "",
                limit: 10,
                page: 1,
                total: 50
            });
            const { name, limit, page, total } = toRefs(params);

            //启用禁用管理员
            const changeStatus = (e, id) => {
                console.log(e, id);
                changeStatusAdmin(e, id).then(res=>{
                     if (res.ret == 200) {
                        if (e > 0) {
                        _this.$message.success({
                            message: "已启用管理员权限",
                            type: "success",
                        });
                        } else {
                        _this.$message.success({
                            message: "已关闭管理员权限",
                            type: "success",
                        });
                        }
                    }
                })
            };
            const handleCurrentChange = (val) => {
                console.log(val);
                if (val !== params.page) {
                    params.page = val
                    return getDataList()
                }
            }
            function addUser() {
                if (!state.adding) {
                    state.addIndex = state.tableData.length;
                    let newObj = {
                    isEdit: true,
                    };
                    // let newObj = state.formObj
                    state.tableData.push(newObj);
                } else {
                    _this.$message.error("请先填写成员信息保存后才能继续添加！");
                    return;
                }
                state.adding = true;
            }

            // 保存
            function handleSave(index, rowObj){
                 console.log(rowObj);
                 console.log(index);
                 if(rowObj.department_id == '未选择'){
                    _this.$message.error({
                        message: "请选择所属部门",
                    });
                    return
                }
                if(isChinese(rowObj.department_id)){
                    rowObj.department_id = rowObj.d_id;
                }
                let data = {
                    group_id: rowObj.group_id,
                    nickname: rowObj.nickname,
                    username: rowObj.username,
                    password: rowObj.pwd,
                    status: rowObj.status ? 1 : 0,
                    // salary: rowObj.salary_name ? rowObj.salary_name : 0,
                    salary: rowObj.salary,
                    department_id: rowObj.department_id,
                    number: rowObj.number ? rowObj.number : 0,
                    money: rowObj.money ? rowObj.money : 0,
                    integral: rowObj.integral
                };

                for (const key in data) {
                    console.log(data[key]);
                    // console.log(key);
                    if (!data[key]) {
                        return _this.$message.error('请先把信息填写完整')
                        // return console.log(key+'--'); 
                    }
                }
                if (rowObj.canEdit) {
                    data.admin_id = state.tableData[index].id;
                    httpEditAdmin(data);
                } else {
                    httpAddAdmin(data)
                }
                state.tableData[index].isEdit = false;
                if (index == state.addIndex) {
                    console.log("新增的对象");
                    state.addIndex = -1;
                    state.adding = false;
                }
            };

             //获取分组列表
            const getRoleList = () => {
                getGroups().then((res) => {
                if (res.ret == 200) {
                    state.jurisdictionArr = res.data.data;
                }
                });
            };

              //编辑管理员
            const httpEditAdmin = (data) => {
                editAdmin(data).then((res) => {
                if (res.ret == 200) {
                    _this.$message.success({
                    message: "编辑成功",
                    type: "success",
                    });
                    getDataList();
                } else {
                   _this.$message.error({
                    message: res.msg,
                    type: "error",
                    });
                    getDataList();
                }
                });
            };

             //添加管理员
            const httpAddAdmin = (data) => {
            addAdmin(data).then((res) => {
                if (res.ret == 200) {
                    _this.$message.success({
                    message: "添加成功",
                    type: "success",
                    });
                    getDataList();
                } else {
                     _this.$message.error({
                    message: res.msg,
                    });
                }
                });
            };
            /**
             * @description:添加or编辑事件
             * @param {*}
             * @return {*}
             */
            const handleEdit = (title, row = null) => {
                showDialog.value = true;
                dialogTitle.value = title;
                rowData.value = row;
            };
            /**
             * @description: dialog事件
             * @param {*}
             * @return {*}
             */
            const handelDialog = e => {
                showDialog.value = e;
                getDataList();
            };
            /**删除行数据
             * @description:
             * @param {*}
             * @return {*}
             */
            const handleDel = id => {
                proxy
                    .$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "error"
                    })
                    .then(async () => {
                        const { code } = await VE_API.system.roleDel({ id });
                        if (code == "00") {
                            getDataList();
                        }
                    })
                    .catch(() => {
                        proxy.$message({
                            type: "info",
                            message: "已取消删除"
                        });
                    });
            };
            /**
             * @description:查看成员
             * @param {*}
             * @return {*}
             */
            const allMember = id => {
                // 获取当前path的id
                let pathId = route.name.slice(route.name.lastIndexOf("-") + 1);
                // 获取要跳转到的路由
                const toName = findName(
                    "member",
                    "system/Users",
                    pathId,
                    menuList,
                    proxy
                );
                router.push({ name: toName, query: { id } });
            };
            /**
             * @description: 获取列表数据
             * @param {*}
             * @return {*}
             */
            const getDataList = async () => {
                await getAdminList(params).then(res=>{
                    state.tableData= res.data.data
                    state.tableData.forEach(item=>{
                        item.canEdit = false 
                        item.status = parseInt(item.status) > 0 ? true : false;
                    })
                    
                     state.total = res.data.total
                })
            };
            // 编辑
            function handleTabelRowEdit (index, rowObj){
                  state.tableData[index].canEdit = true;
                  state.tableData[index].isEdit = true;
            };
            // 取消
            function handleCancle(index, rowObj) {
                state.tableData[index].isEdit = false;
            }
            function handleDelete(id){
                 _this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                   deleteAdminListRow(id).then((res) => {
                    if(res.ret == 200){
                        _this.$message({
                        type: 'success',
                        message: '删除成功!'
                        });
                        getDataList();
                    }else{
                        _this.$message.error(res.msg);
                    }
                    })

                }).catch(() => {
                    _this.$message({
                    type: 'info',
                    message: '已取消删除'
                    });
                });
            }
            function getDepartList(){
                let paramsObj = {
                    page: 1,
                    pageSize: 20
                };
                departList(paramsObj).then(res=>{
                    console.log();
                    state.department = res.data.data
                })
            }
             const isChinese = (str) => {
                var re=/[^\u4E00-\u9FA5]/;
                if (re.test(str)) return false ;
                return true ;
            }
            onMounted(async () => {
                await getDataList();
                await getDepartList();
                await getRoleList();
                maxHeight(pagination, queryForm, toolBar, ve_max_height);
            });
            return {
                ve_max_height,
                ve_rowIndex,
                getDataList,
                tableData,
                params,
                ...{ name, limit, page, total },
                ...{ pagination, queryForm, toolBar },
                ...{ handleEdit, rowData, dialogTitle, showDialog },
                ...{
                    onSubmit,
                    resetForm,
                    handleSizeChange,
                    rowClassName,
                    cellClassName,
                    rowClick,
                    maxHeight
                },
                handelDialog,
                handleDel,
                allMember,
                value1,
                state,
                changeStatus,
                handleTabelRowEdit,
                handleCancle,handleDelete,handleSave,addUser,
                handleCurrentChange,
            };
        }
    };
</script>

<style lang="scss" scoped>
    .noEdit {
        :deep(input) {
            border: 0;
            padding: 0;
            font-size: 14px;
        }
    }

    :deep(.el-table__row){
            font-size: 14px;
    }

    .readOnly,
      .editing {
        display: flex;
        span {
          color: #1890ffff;
          margin-right: 8px;
          padding-right: 8px;
          cursor: pointer;
          &:nth-child(1) {
            border-right: 1px solid #e9e9e9ff;
          }
        }
      }

    .el-main {
        background: #EFF3FB !important;
    }
    .bg {
        background: white;
        padding: 55px 30px 35px 35px;
        border-radius: 10px;
    }
    .tab {
        margin-top: 20px;
        margin-bottom: 20px;
        padding-left: 20px;
    }
    .tab-value {
        background: white;
        padding-left: 20px;
        padding-top: 5px;
        border-radius: 8px;
        min-height: 400px;
        position: relative;
        padding-bottom: 80px;
    }
    .tab-k {
        color: #7A8499;
        font-size: 13px;
        font-weight: 600;
    }
    .tab-v {
        color: #7A8499;
        font-size: 13px;
        line-height: 30px;
    }
    .fnt {
        color: #45484D;
        font-weight: bold;
    }
    .d {
        padding-top: 10px;
        padding-bottom: 20px;
        border-bottom: 1px solid #f9f9f9;
    }
    .d-fix {
        display: flex;
        justify-content: space-between;
    }
    .pagin {
        position: absolute;
        bottom: 20px;
        left: 0;
        right: 0;
        margin: auto;
        text-align: center;
    }

    .addUser {
        margin-top: 23px;
        border-radius: 4px;
        color: #000000a6;
        border: 1px dashed #d9d9d9ff;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        margin-bottom: 10px;
        strong {
          margin-right: 5px;
        }
    }
</style>
